package com.app.xinfadi.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.app.xinfadi.R;
import com.app.xinfadi.util.LogUtil;
import com.app.xinfadi.util.SharedPreferencesUtil;
import com.app.xinfadi.widget.dialog.CustomProgressDialog;
import com.app.xinfadi.widget.dialog.ToastDialog;
import com.app.xinfadi.widget.gson.GsonRequest;
import com.app.xinfadi.widget.hierarchyviewerservice.ViewServer;

import java.util.Stack;


/**
 * base
 *
 * @author WuTengFei
 */
public abstract class BaseActivity extends AppCompatActivity implements OnClickListener {
    private static final String TAG = "BaseActivity";
    protected Context context;
    // 获得自定义的应用程序Application
    protected MyApplication myApplication = null;

    private CustomProgressDialog progressDialog;
    private ToastDialog toastDialog;
    private String defaultProgressMessage = "加载中";
    private static boolean isHierarchyView = false;

    public Toolbar mToolbar;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        context = this;
        myApplication = MyApplication.getInstance();
        pushActivity(this);
        hierarchyViewerService();
//        setStatusBar(this);

    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        View view = LayoutInflater.from(this).inflate(layoutResID, null);

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
// set a custom navigation bar resource
//        tintManager.setNavigationBarTintResource(R.drawable.my_tint);
//// set a custom status bar drawable
//        tintManager.setStatusBarTintDrawable(MyDrawable);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.common_titlebar_back:
//                closeSoftKeyBoard(this);
//                finish();
//                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        popActivity(this);
        super.onDestroy();
        detoryHierarchyViewerService();
    }

    public void setStatusBar(Activity activity) {
//        if (true) return;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            activity.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            );//| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            window.setStatusBarColor(Utils.resolveColor(activity, R.attr.theme_statusbar_color, Color.BLUE));
            window.setStatusBarColor(Color.parseColor("#20000000"));
//            window.setNavigationBarColor(activity.getResources().getColor(ThemeUtils.themeColorArr[AppSettings.getThemeColor()][1]));
            window.setNavigationBarColor(activity.getResources().getColor(R.color.color_primary));

//            window.setNavigationBarColor(Utils.resolveColor(activity, R.attr.theme_color, Color.BLUE));

//            Window window = activity.getWindow();
//            window.requestFeature(Window.FEATURE_NO_TITLE);
//            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
//                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            window.setStatusBarColor(Color.TRANSPARENT);
//            window.setNavigationBarColor(Utils.resolveColor(activity, R.attr.theme_statusbar_color, Color.TRANSPARENT));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        resumeHierarchyViewerService();
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
    }

    public void popActivity() {
        ScreenManager.getInstance().popActivity();
    }

    public void popActivity(Activity activity) {
        ScreenManager.getInstance().popActivity(activity);
    }

    public Activity currentActivity() {
        return ScreenManager.getInstance().currentActivity();
    }

    public void pushActivity(Activity activity) {
        ScreenManager.getInstance().pushActivity(activity);
    }

    /**
     * 关闭此acitivity 在栈 处于他之上的activity
     *
     * @param cls
     */
    public void popAllActivityExceptOne(Class<?> cls) {
        LogUtil.d(TAG, "popAllActivityExceptOne");
        ScreenManager.getInstance().popAllActivityExceptOne(cls);
    }

    /**
     * 退出程序
     */
    public void exitPorgress() {
        Stack<Activity> stacks = ScreenManager.getInstance().getActivityStack();
        stacks.toArray();
        for (Activity activity : stacks) {
            popActivity(activity);
        }
    }

    public <T> void addToRequestQueue(GsonRequest<T> request, String tag) {
        MyApplication.getInstance().addToRequestQueue(request, tag);
    }

    public <T> void addToRequestQueue(GsonRequest<T> request) {
        MyApplication.getInstance().addToRequestQueue(request);
    }

    public void cancelPendingRequests(Object tag) {
        MyApplication.getInstance().cancelPendingRequests(tag);
    }

    /**
     * 是否登陆
     *
     * @return
     */
    public boolean isLogin() {
        if (SharedPreferencesUtil.getInstance().getUserState() == 0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 显示 旋转progress
     *
     * @param message 文字内容
     */
    public void showProgressDialog(String message) {
        closeSoftKeyBoard(this);
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = .7f;
        getWindow().setAttributes(lp);
        progressDialog = createProgressDialog();
        progressDialog.setMessage(message);
        progressDialog.show();
    }

    /**
     * 显示 旋转progress
     */
    public void showProgressDialog() {
        showProgressDialog(defaultProgressMessage);
    }

    /**
     * 显示类土司
     *
     * @param message
     */
    public void showToastDialog(String message, ToastDialog.OnMyDissmissListener onDissmissListener) {
        closeSoftKeyBoard(this);
        if (toastDialog != null && toastDialog.isShowing()) {
            toastDialog.dismiss();
            toastDialog = null;
        }
        toastDialog = ToastDialog.createDialog(context, onDissmissListener);
        toastDialog.setMessage(message);
        toastDialog.show();
        toastDialog.delayHideShow();
    }

    public void showToastDialog(String message) {
        closeSoftKeyBoard(this);
        // if (toastDialog != null && toastDialog.isShowing()) {
        // toastDialog.dismiss();
        // toastDialog = null;
        // }
        toastDialog = ToastDialog.createDialog(context);
        toastDialog.setMessage(message);
        toastDialog.show();
        toastDialog.delayHideShow();
    }

    public CustomProgressDialog createProgressDialog() {
        dismissProgressDialog();
        progressDialog = CustomProgressDialog.createDialog(this);
        progressDialog.setMessage("加载中...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
        // progressDialog.setContentView(R.layout.dialog_loading_process);
        return progressDialog;
    }

    /**
     * 隐藏正在加载的进度条
     */
    public void dismissProgressDialog() {
        try {
            if (progressDialog != null) {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                progressDialog = null;
            }
        } catch (Exception e) {
        }
    }

    public CustomProgressDialog getProgressDialog() {
        return progressDialog;
    }

    /**
     * 关闭系统软键盘
     */
    public static void closeSoftKeyBoard(Activity activity) {
        InputMethodManager inputMethodManager = (InputMethodManager) activity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null && activity.getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 按照其图片比例 缩放控件
     *
     * @param drawable
     * @param view
     */
    public void equalProportionDrawable(Drawable drawable, View view) {
        int imageHeight = drawable.getIntrinsicHeight() * myApplication.screenWidth / drawable.getIntrinsicWidth();
        LayoutParams drawableLayoutParams = view.getLayoutParams();
        drawableLayoutParams.height = imageHeight;
        drawableLayoutParams.width = MyApplication.getInstance().screenWidth;
        view.setLayoutParams(drawableLayoutParams);
    }

    /**
     * dip转换px
     */
    public int dip2px(int dip) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f);
    }

    /**
     * pxz转换dip
     */
    public int px2dip(int px) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    public void screenDarker() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = .3f;
        getWindow().setAttributes(lp);
    }

    public void screenLight() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1.0f;
        getWindow().setAttributes(lp);
    }

    private void hierarchyViewerService() {
        if (isHierarchyView)
            ViewServer.get(this).addWindow(this);
    }

    private void detoryHierarchyViewerService() {
        if (isHierarchyView)
            ViewServer.get(this).removeWindow(this);
    }

    private void resumeHierarchyViewerService() {
        if (isHierarchyView)
            ViewServer.get(this).setFocusedWindow(this);
    }

    public Toolbar getToolbar() {
        if (mToolbar == null) {
            mToolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(this.mToolbar);
        }
        return mToolbar;
    }
}
